var express = require('express');
var io = require('socket.io');

var  mongodb_client = require('mongodb').MongoClient, assert = require('assert');
var url = 'mongodb://localhost:27017/DHT11';
//var  server  = new mongodb.Server('localhost', 27017, {auto_reconnect:true});
//var  db = new mongodb.Db('DHT11', server, {safe:true});

var options = {  
	server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000, auto_reconnect: true,
        poolSize: 10 } },
	replset: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } }
};

var router = express.Router();

/* GET data . */
router.prepareSocketIO = function (se) {
	var socket_io = io.listen(se);
	socket_io.sockets.on('connection', function (socket) {
		console.log('new socket connection.');

		mongodb_client.connect(url, options, function(err, db){
			if(!err){
				//console.log('connected db');
				db.collection('test', {safe:true}, function(err, collection){
					if(err){
						db.close();
						console.log(err);
					}
					else{
						setInterval(function () {
							var new_time = new Date().getTime();
							var cursor = collection.find({"Time":{$gte:(new_time/1000 - 86400)}}).sort({"Time":-1}).limit(1);
							// console.log('data.js: '+(new_time/1000 - 86400));
							if (!cursor) {
										console.log('Need Data Updata!');
							}
							else{
								cursor.toArray(function(err,doc){
        								if(doc[0]){
        								socket.emit('dy_data',{time:doc[0].Time, tmp:doc[0].TMP, rh:doc[0].RH});
    										// console.log(doc[0]);
									}
									else{
										console.log('data.js : doc error!');
									}
								});
							}
						}, 3000);
					};
				});
			}
			else{
				db.close();
				console.log(err);
			}
		});
	});
};

module.exports = router;